package org.atf.utils;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;

public class SchedulerJobsXmlDAO {
	private static Logger logger = Logger.getLogger(SchedulerJobsXmlDAO.class);
	public static String JOB_XML_DATE_FORMAT="yyyy-MM-dd'T'HH:mm:ss";
	public static String addSchedulerToJobFile(
			HashMap<String, String> jobDetails,
			HashMap<String, String> jobMapDetails,
			HashMap<String, String> jobTrigger) {
		// TODO Auto-generated method stub
		String results="";
		String jobXmlFile=ATFUtils.getResourcePath("jobs.xml");
		logger.debug("jobXmlFile: "+jobXmlFile);
		logger.debug("jobDetails: "+jobDetails);
		logger.debug("jobMapDetails: "+jobMapDetails);
		logger.debug("jobTrigger: "+jobTrigger);
		
		if(jobXmlFile != null && !jobXmlFile.equalsIgnoreCase("")){
			Document jobDocument= JDOMUtil.fileToDocument(jobXmlFile);
			if(jobDocument != null ){
				Element jobElement=new Element("job",jobDocument.getRootElement().getNamespace());
				Element jobMapDetailsElement=new Element("job-data-map",jobDocument.getRootElement().getNamespace());
				Element jobTriggerElement=new Element("trigger",jobDocument.getRootElement().getNamespace());
				Element dateIntervalElement=new Element("calendar-interval",jobDocument.getRootElement().getNamespace());
				
				//build jobElement
				jobElement.addContent(new Element("name",jobDocument.getRootElement().getNamespace()).setText(jobDetails.get("name")));
				jobElement.addContent(new Element("group",jobDocument.getRootElement().getNamespace()).setText(jobDetails.get("group")));
				jobElement.addContent(new Element("description",jobDocument.getRootElement().getNamespace()).setText(jobDetails.get("description")));
				jobElement.addContent(new Element("job-class",jobDocument.getRootElement().getNamespace()).setText(jobDetails.get("job-class")));
				
				Iterator jobMapDetailsKeys=jobMapDetails.keySet().iterator();
				while(jobMapDetailsKeys.hasNext()){
					String name=(String)jobMapDetailsKeys.next();
					String value=jobMapDetails.get(name);
					Element entry=new Element("entry",jobDocument.getRootElement().getNamespace())
									.addContent(new Element("key",jobDocument.getRootElement().getNamespace()).setText(name))
									.addContent(new Element("value",jobDocument.getRootElement().getNamespace()).setText(value));
					jobMapDetailsElement.addContent(entry);
				}
				jobElement.addContent(jobMapDetailsElement);
				
				dateIntervalElement.addContent(new Element("name",jobDocument.getRootElement().getNamespace()).setText(jobTrigger.get("name")));
				dateIntervalElement.addContent(new Element("group",jobDocument.getRootElement().getNamespace()).setText(jobTrigger.get("group")));
				dateIntervalElement.addContent(new Element("job-name",jobDocument.getRootElement().getNamespace()).setText(jobTrigger.get("job-name")));
				dateIntervalElement.addContent(new Element("job-group",jobDocument.getRootElement().getNamespace()).setText(jobTrigger.get("job-group")));
				dateIntervalElement.addContent(new Element("start-time",jobDocument.getRootElement().getNamespace()).setText(jobTrigger.get("start-time")));
				if(jobTrigger.containsKey("end-time")){
					dateIntervalElement.addContent(new Element("end-time",jobDocument.getRootElement().getNamespace()).setText(jobTrigger.get("end-time")));
				}
				
				dateIntervalElement.addContent(new Element("misfire-instruction",jobDocument.getRootElement().getNamespace()).setText("MISFIRE_INSTRUCTION_DO_NOTHING"));
				dateIntervalElement.addContent(new Element("repeat-interval",jobDocument.getRootElement().getNamespace()).setText(jobTrigger.get("repeat-interval")));
				dateIntervalElement.addContent(new Element("repeat-interval-unit",jobDocument.getRootElement().getNamespace()).setText(jobTrigger.get("repeat-interval-unit")));
				
				jobTriggerElement.addContent(dateIntervalElement);
				Element scheduleElement=jobDocument.getRootElement().getChild("schedule",jobDocument.getRootElement().getNamespace());
				if(scheduleElement == null){
					scheduleElement= new Element("schedule",jobDocument.getRootElement().getNamespace());
					jobDocument.getRootElement().addContent(scheduleElement);
				}
				scheduleElement.addContent(jobElement).addContent(jobTriggerElement);
				if(JDOMUtil.documentToFile(jobDocument, jobXmlFile)){
					results="OK";
				}else{
					results="ERROR:Unable to save jobs.xml";
				}
			}else{
				results="ERROR: Unabled to build jobs.xml";
			}
		}else{
			results="ERROR:Unable to find the jobs.xml file";
		}
		
		return results;
	}
	public static boolean removeSchedulerFromJobFile(String jobName){
		boolean results=false;
		String fileName=ATFUtils.getResourcePath("jobs.xml");
		Document jobDocument= JDOMUtil.fileToDocument(fileName);
		Element rootElement=jobDocument.getRootElement();
		logger.debug("RootElement: "+rootElement.toString());
		List<Element> rootChild=rootElement.getChildren();
		for(int i=0 ; i<rootChild.size();i++){
			Element el=rootChild.get(i);
			logger.debug("Element: "+el.toString());
			if(el.getName().equalsIgnoreCase("schedule")){
				logger.debug("Element111: "+el.toString());
				List<Element> jobChild=el.getChildren();
				logger.debug("jobChild: "+jobChild.size());
				for(int j=0 ; j<jobChild.size();j++){
					Element jobElement=jobChild.get(j);
					if(jobElement.getName().equalsIgnoreCase("job")){
						logger.debug("jobElement: "+jobElement.toString());
						if(jobElement.getChild("name", rootElement.getNamespace()).getText().equalsIgnoreCase(jobName)){
							logger.debug(el.removeContent(jobElement));
							break;
						}
							
					}
				}
				jobChild=el.getChildren();
				logger.debug("jobChild: "+jobChild.size());
				for(int j=0 ; j<jobChild.size();j++){
					logger.debug(j);
					Element jobElement=jobChild.get(j);
					if(jobElement.getName().equalsIgnoreCase("trigger")){
						logger.debug("jobElement: "+jobElement.toString());
						Element triggerEl=jobElement.getChild("calendar-interval",rootElement.getNamespace()).getChild("job-name",rootElement.getNamespace());
						logger.debug("triggerEl: "+triggerEl.toString());
						if(triggerEl.getText().equalsIgnoreCase(jobName)){
							logger.debug(el.removeContent(jobElement));
							break;
						}
					}
				}
			}
		}
		results=JDOMUtil.documentToFile(jobDocument, fileName);
		return results;
		
	}
	public static boolean updateStartTime(String jobName, Date newStartTime){
		
		return false;
	}
	
	public static boolean updateEndTime(String jobName, Date newEndTime){
		return false;
	}
	
	public static boolean updateRepetitionIntervalUnit(String jobName, String repeatIntervalUnit){
		
		return false;
	}
	public static boolean checkExists(String jobName) {
		// TODO Auto-generated method stub
		logger.debug("Job Check:"+jobName);
		String fileName=ATFUtils.getResourcePath("jobs.xml");
		if(!fileName.equalsIgnoreCase("") ){
			logger.debug("fileName: "+fileName);
			Document jobDocument= JDOMUtil.fileToDocument(fileName);
			
			String query="/job-scheduling-data/schedule/job[name=\""+jobName+"\"]";
			logger.debug("query: "+query);
			try {
				List<Element> ele=JDOMUtil.getElementByXpath(jobDocument,query);
				logger.debug("Elements Found: "+ele.size());
				if(ele.size() > 1){
					return true;
				}
			} catch (JDOMException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return false;
	}
}
